#!/usr/bin/python2

import pyglet
from pyglet import gl
import euclid
import context
from avatar import update_period
import logging

try:
    config = gl.Config(sample_buffer=1, samples=4, depth_size=16, double_buffer=True)
    window = pyglet.window.Window(resizable=True, config=config)
except:
    window = pyglet.window.Window(resizable=True)

def initGL():
    gl.glEnable(gl.GL_DEPTH_TEST)
    #glAlphaFunc(GL_GREATER, 0.4)
    #glEnable(GL_ALPHA_TEST)

@window.event
def on_resize(width, height):
    # Override the default on_resize handler to create a 3D projection
    gl.glViewport(0, 0, width, height)
    
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.gluPerspective(70.0, width / float(height), .1, 1000.)
    
    return pyglet.event.EVENT_HANDLED

@window.event
def on_draw():
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    context._context.draw()

key_actions = {pyglet.window.key.LEFT : euclid.Vector3(2., 0., 0.),
               pyglet.window.key.RIGHT : euclid.Vector3(-2., 0., 0.),
               pyglet.window.key.UP : euclid.Vector3(0., 0., 2.),
               pyglet.window.key.DOWN : euclid.Vector3(0., 0., -2.),}

@window.event
def on_key_press(symbol, modifiers):
    try:
        context._context.camera.accelerate(key_actions[symbol])
    except KeyError:
        print "Unknown key : %s" % symbol


@window.event
def on_key_release(symbol, modifiers):
    try:
        context._context.camera.accelerate(-key_actions[symbol])
    except KeyError:
        print "Unknown key : %s" % symbol

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    context._context.camera.rotate(dx, dy)

if __name__ == '__main__': 
    logging.basicConfig(format="%(levelname)s VISITOR %(asctime)-15s %(message)s" , level=logging.DEBUG)
    logging.info("Starting")
    
    initGL()
    
    context._context.init_network()

    #24 fps
    pyglet.clock.schedule_interval(context._context.update_draw, 1.0/24.0)
    pyglet.clock.schedule_interval(context._context.update_network, update_period)

    pyglet.app.run()


